import path from "path";
import { DataSource, EntitySchema, ObjectLiteral } from "typeorm";

import {} from "qqlx-core";
import { toString } from "qqlx-cdk";

export class SqliteClient {
  logger: boolean = false;
  databasePath: string;
  databaseName: string;

  serverClient!: DataSource;

  constructor(databasePath: string, databaseName: string, logger?: boolean) {
    this.databasePath = toString(databasePath);
    this.databaseName = toString(databaseName);
    this.logger = !!logger;
  }

  async start(schemaList: object[]) {
    this.serverClient = new DataSource({
      type: "sqlite",
      database: path.join(this.databasePath, this.databaseName),
      logging: false,
      synchronize: true,
      entities: schemaList as unknown as EntitySchema[],
    });
    await this.serverClient.initialize();

    // 启用 SQLite 外键约束
    await this.serverClient.query("PRAGMA foreign_keys = ON;");

    this.logger && console.log("🏀 Sqlite > 初始化实例成功", this.databasePath, this.databaseName);

    return this.serverClient;
  }

  async stop() {
    this.serverClient && (await this.serverClient.destroy());
    this.logger && console.log("🏀 Sqlite > 数据库控制器：已经关闭数据库实例");
  }

  getRepository<T extends ObjectLiteral>(entity: new () => T) {
    return this.serverClient.getRepository(entity);
  }
}
